using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using I2.Loc;
using Rilisoft.MiniJson;
using UnityEngine;
using UnityEngine.SceneManagement;

public class InAppPromoController : MonoBehaviour
{
	public class PromoBonuses
	{
		public int cashAmount;

		public int goldAmount;

		private List<List<string>> marketItemsIds = new List<List<string>>();

		public bool promoHasBonuses;

		public int сashAmountAlternative;

		public int goldAmountAlternative;

		public PromoBonuses()
		{
			cashAmount = (goldAmount = 0);
			marketItemsIds = new List<List<string>>();
			promoHasBonuses = false;
			сashAmountAlternative = (goldAmountAlternative = 0);
		}

		public PromoBonuses(int cash, int gold, List<List<string>> ids, bool promoHasBonuses, int cashAlternativ, int goldAlternative)
		{
			cashAmount = cash;
			goldAmount = gold;
			marketItemsIds = ids;
			this.promoHasBonuses = promoHasBonuses;
			сashAmountAlternative = cashAlternativ;
			goldAmountAlternative = goldAlternative;
		}

		public bool GiveAlternativeBonuses()
		{
			return marketItemsIds.Count != 0 && marketItemsIds.Exists((List<string> x) => x.All((string id) => MarketController.Instance.allProducts.ContainsKey(id) && MarketController.Instance.allProducts[id].Purchased));
		}

		public bool AllPromoBonusesAreBought()
		{
			return marketItemsIds.Count != 0 && marketItemsIds.All((List<string> x) => x.All((string id) => MarketController.Instance.allProducts.ContainsKey(id) && MarketController.Instance.allProducts[id].Purchased));
		}

		public List<string> GetPromoMarketBonusesIds(bool ignoreBought = true)
		{
			List<string> list = new List<string>();
			for (int i = 0; i < marketItemsIds.Count; i++)
			{
				for (int j = 0; j < marketItemsIds[i].Count && MarketController.Instance.allProducts.ContainsKey(marketItemsIds[i][j]); j++)
				{
					if (MarketController.Instance.allProducts[marketItemsIds[i][j]].Purchased)
					{
						if (j == marketItemsIds[i].Count - 1 && !ignoreBought)
						{
							list.Add(marketItemsIds[i][j]);
						}
						continue;
					}
					list.Add(marketItemsIds[i][j]);
					break;
				}
			}
			return list;
		}
	}

	public enum BonusImageType
	{
		Weapon = 0,
		Vehicle = 1,
		Money = 2,
		Single = 3
	}

	public class InAppPromo
	{
		private bool enabled;

		public GamerType gamerType;

		public int hoboTime;

		public string inAppId = string.Empty;

		public int amount;

		public int startTime;

		public int endTime;

		public PromoBonuses promoBonuses = new PromoBonuses();

		public string titleEn = string.Empty;

		public string titleRus = string.Empty;

		public Dictionary<int, string> titles = new Dictionary<int, string>();

		public string descriptionEn = string.Empty;

		public string descriptionRus = string.Empty;

		public Dictionary<int, string> descriptions = new Dictionary<int, string>();

		public string packsLeftEn = string.Empty;

		public string packsLeftRus = string.Empty;

		public Dictionary<int, string> packsLeftDict = new Dictionary<int, string>();

		public bool isCashPromo = true;

		public int inAppPar = -1;

		public BonusImageType bonusImageType;

		public string showForNewOrOldUser = string.Empty;

		public string showForPayingOrNotUser = string.Empty;

		public int hoursFromStart;

		public int neededLeague;

		public bool isSingleUse;

		public string uniqueKey = string.Empty;

		public float inAppShowingPrice = -1f;

		public bool Enabled
		{
			get
			{
				bool flag = false;
				bool flag2 = false;
				bool flag3 = false;
				bool flag4 = PromoActionManager.NewUser(PromoActionManager.fyber.newUserStatusHours);
				if ((flag4 && showForNewOrOldUser == "new") || (!flag4 && showForNewOrOldUser == "old") || showForNewOrOldUser == string.Empty)
				{
					flag2 = true;
				}
				if ((PromoActionManager.PayingUser() && showForPayingOrNotUser == "payed") || (!PromoActionManager.PayingUser() && showForPayingOrNotUser == "non_payed") || showForPayingOrNotUser == string.Empty)
				{
					flag = true;
				}
				flag3 = PromoActionManager.PlayedHours(hoursFromStart);
				bool flag5 = enabled && gamerType == InAppShop.currentGamerType && PromoActionManager.CurrentUnixTimeSecond > startTime && PromoActionManager.CurrentUnixTimeSecond < endTime && promoBonuses.promoHasBonuses && (flag || flag2) && flag3 && neededLeague <= CupsManager.CurrentTier && (!isSingleUse || (isSingleUse && !BCWStorage.Get<bool>(uniqueKey)));
				if (flag5 && gamerType == GamerType.Hobo && hoboTime > 0 && PromoActionManager.PlayedHours(hoboTime))
				{
					flag5 = false;
				}
				return flag5;
			}
			set
			{
				enabled = value;
			}
		}

		public string GetTitle()
		{
			if (!promoBonuses.GiveAlternativeBonuses())
			{
				int languageIndex = LocalizationManager.GetLanguageIndex(LocalizationManager.CurrentLanguage);
				if (titles.ContainsKey(languageIndex))
				{
					return titles[languageIndex];
				}
				return titleEn;
			}
			return ScriptLocalization.Get("Game_Common/GiveAlternativeBonuses_Title");
		}

		public string GetDescription()
		{
			if (!promoBonuses.GiveAlternativeBonuses())
			{
				int languageIndex = LocalizationManager.GetLanguageIndex(LocalizationManager.CurrentLanguage);
				if (descriptions.ContainsKey(languageIndex))
				{
					return descriptions[languageIndex];
				}
				return descriptionEn;
			}
			return ScriptLocalization.Get("Game_Common/GiveAlternativeBonuses_Description");
		}

		public string GetPacksLeftTitle()
		{
			return GetPacksLeftTitle("ffff00ff");
		}

		public string GetPacksLeftTitle(string bbcode)
		{
			int languageIndex = LocalizationManager.GetLanguageIndex(LocalizationManager.CurrentLanguage);
			int packsLeftAmount = GetPacksLeftAmount();
			string arg = string.Format("[{0}]", bbcode) + packsLeftAmount + "[-]";
			string format = packsLeftEn;
			if (packsLeftDict.ContainsKey(languageIndex))
			{
				format = packsLeftDict[languageIndex];
			}
			return string.Format(format, arg);
		}

		public int GetPacksLeftAmount()
		{
			int num = amount;
			int currentUnixTimeSecond = PromoActionManager.CurrentUnixTimeSecond;
			int num2 = startTime;
			int num3 = endTime;
			int num4 = Mathf.CeilToInt((1f - (float)(currentUnixTimeSecond - num2) / (float)(num3 - num2)) * (float)num);
			return (num4 <= 0) ? 1 : num4;
		}
	}

	public class InAppPromosList
	{
		public List<InAppPromo> allPromos = new List<InAppPromo>();

		public InAppPromo GetPromoById(string id)
		{
			return allPromos.Find((InAppPromo x) => x.inAppId == id && x.Enabled);
		}

		public List<InAppPromo> GetPromosById(string id)
		{
			return allPromos.Where((InAppPromo x) => x.inAppId == id).ToList();
		}
	}

	private static InAppPromoController _instance;

	private bool _isRequestAndLoadRunning;

	public bool jsonReaded;

	private int lastLeagueUpdate = -1;

	public InAppPromosList inAppPromos = new InAppPromosList();

	private float timerJson;

	private float maxTimerJson = 10f;

	private string currentJson = "-1";

	private string newJson = "-1";

	public static InAppPromoController instance
	{
		get
		{
			if (_instance == null)
			{
				GameObject gameObject = new GameObject();
				gameObject.name = "InAppPromoController(Don't Destroy)";
				gameObject.AddComponent<InAppPromoController>();
			}
			return _instance;
		}
	}

	public static event Action promosJsonLoaded;

	public static event Action promosParsedFromJson;

	private void Awake()
	{
		if (_instance != null)
		{
			UnityEngine.Object.DestroyImmediate(this);
			return;
		}
		_instance = this;
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
	}

	private void Start()
	{
		StartCoroutine(RequestAndLoadPromoJson());
		StartCoroutine(TimerForLoadJson());
	}

	private IEnumerator TimerForLoadJson()
	{
		while (true)
		{
			yield return new WaitForSeconds(1f);
			timerJson += 1f;
		}
	}

	private IEnumerator RequestAndLoadPromoJson()
	{
		while (!JSONManager.Instance.ServerTimeLoad())
		{
			yield return null;
		}
		yield return new WaitForSeconds(1.5f);
		string jsonText = JSONManager.Instance.GetJSON(URLs.InAppPromo);
		string oldJson = string.Empty;
		while (jsonText == oldJson)
		{
			yield return new WaitForSeconds(3f);
			oldJson = jsonText;
			jsonText = JSONManager.Instance.GetJSON(URLs.InAppPromo);
		}
		if (InAppPromoController.promosJsonLoaded != null)
		{
			InAppPromoController.promosJsonLoaded();
		}
		TryParseJson(jsonText);
		Dictionary<string, object> parsedJson = Json.Deserialize(jsonText) as Dictionary<string, object>;
		if (parsedJson.ContainsKey(settings.KEY_ROCKET_LEAGUE_PING_LIMIT))
		{
			BCWStorage.Set(value: Convert.ToInt32(parsedJson[settings.KEY_ROCKET_LEAGUE_PING_LIMIT]), key: settings.KEY_ROCKET_LEAGUE_PING_LIMIT, immediatelySave: true);
		}
		else
		{
			BCWDebug.LogError("LOG: Ожидали в JSON'е получить максимальный пинг рокет лиги, но не получили");
		}
		_isRequestAndLoadRunning = false;
		jsonReaded = true;
	}

	public void UpdateJSON()
	{
		StartUpdatePromoJson();
		InAppSubscriptionsController.instance.StartUpdateSubscriptionJson();
	}

	public void ParseDownloadedJSON()
	{
		StartCoroutine(ParseDownloadedJSONCoroutine());
	}

	private IEnumerator ParseDownloadedJSONCoroutine()
	{
		if (!(SceneManager.GetActiveScene().name != "Lobby"))
		{
			TryParseJson(JSONManager.Instance.GetJSON(URLs.InAppPromo));
		}
		yield break;
	}

	public void StartUpdatePromoJson()
	{
		StartCoroutine(UpdatePromoJson());
	}

	private IEnumerator UpdatePromoJson()
	{
		if (lastLeagueUpdate != CupsManager.CurrentTier)
		{
			instance.ParseDownloadedJSON();
		}
		if (timerJson < maxTimerJson)
		{
			yield break;
		}
		timerJson = 0f;
		if (!(SceneManager.GetActiveScene().name != "Lobby"))
		{
			newJson = JSONManager.Instance.GetJSON(URLs.InAppPromo);
			if (currentJson != newJson)
			{
				TryParseJson(newJson);
				currentJson = newJson;
				BCWDebug.Log("Downloaded new promo JSON.");
			}
			else
			{
				JSONManager.Instance.UpdateSignature(URLs.InAppPromo);
				BCWDebug.Log("Promo JSON didn't changed. Updating.");
			}
		}
	}

	private bool TryParseJson(string jsonText)
	{
		Dictionary<string, object> dictionary = Json.Deserialize(jsonText) as Dictionary<string, object>;
		if (dictionary == null)
		{
			_isRequestAndLoadRunning = false;
			return false;
		}
		if (dictionary.ContainsKey("promos"))
		{
			List<object> inAppPromosObj = dictionary["promos"] as List<object>;
			ParsePromoObject(inAppPromosObj, inAppPromos);
			return true;
		}
		BCWDebug.Log("InApp Promo response doesn't contain “promos” property.", "Promo");
		return false;
	}

	private void ParsePromoObject(List<object> inAppPromosObj, InAppPromosList promos)
	{
		if (inAppPromosObj == null)
		{
			return;
		}
		promos.allPromos.Clear();
		for (int i = 0; i < inAppPromosObj.Count; i++)
		{
			Dictionary<string, object> dictionary = inAppPromosObj[i] as Dictionary<string, object>;
			promos.allPromos.Add(new InAppPromo());
			promos.allPromos[i].Enabled = Convert.ToInt32(dictionary["enabled"]) == 1;
			promos.allPromos[i].gamerType = (GamerType)Convert.ToInt32(dictionary["gamerType"]);
			promos.allPromos[i].hoboTime = Convert.ToInt32(dictionary["hoboTime"]);
			promos.allPromos[i].titleEn = (string)dictionary["titleEn"];
			promos.allPromos[i].titleRus = (string)dictionary["titleRus"];
			promos.allPromos[i].descriptionEn = (string)dictionary["descriptionEn"];
			promos.allPromos[i].descriptionRus = (string)dictionary["descriptionRus"];
			promos.allPromos[i].packsLeftEn = (string)dictionary["packsLeftEn"];
			promos.allPromos[i].packsLeftRus = (string)dictionary["packsLeftRus"];
			foreach (string allLanguage in LocalizationManager.GetAllLanguages())
			{
				int languageIndex = LocalizationManager.GetLanguageIndex(allLanguage);
				string key = "title_" + languageIndex;
				string key2 = "description_" + languageIndex;
				string key3 = "packsLeft_" + languageIndex;
				if (dictionary.ContainsKey(key))
				{
					promos.allPromos[i].titles.Add(languageIndex, (string)dictionary[key]);
				}
				else if (dictionary.ContainsKey("title_0"))
				{
					promos.allPromos[i].titles.Add(languageIndex, (string)dictionary["title_0"]);
				}
				if (dictionary.ContainsKey(key2))
				{
					promos.allPromos[i].descriptions.Add(languageIndex, (string)dictionary[key2]);
				}
				else if (dictionary.ContainsKey("description_0"))
				{
					promos.allPromos[i].descriptions.Add(languageIndex, (string)dictionary["description_0"]);
				}
				if (dictionary.ContainsKey(key3))
				{
					promos.allPromos[i].packsLeftDict.Add(languageIndex, (string)dictionary[key3]);
				}
				else if (dictionary.ContainsKey("packsLeft_0"))
				{
					promos.allPromos[i].packsLeftDict.Add(languageIndex, (string)dictionary["packsLeft_0"]);
				}
			}
			promos.allPromos[i].inAppId = (string)dictionary["inAppId"];
			promos.allPromos[i].inAppPar = Convert.ToInt32((!dictionary.ContainsKey("inAppPar")) ? ((object)(-1)) : dictionary["inAppPar"]);
			promos.allPromos[i].amount = Convert.ToInt32(dictionary["totalAmount"]);
			promos.allPromos[i].startTime = Convert.ToInt32(dictionary["startTime"]);
			promos.allPromos[i].endTime = Convert.ToInt32(dictionary["endTime"]);
			promos.allPromos[i].bonusImageType = (BonusImageType)Convert.ToInt32(dictionary["bonusImageType"]);
			promos.allPromos[i].showForNewOrOldUser = (string)((!dictionary.ContainsKey("newOldUser")) ? string.Empty : dictionary["newOldUser"]);
			promos.allPromos[i].showForPayingOrNotUser = (string)((!dictionary.ContainsKey("payedNonPayedUser")) ? string.Empty : dictionary["payedNonPayedUser"]);
			promos.allPromos[i].hoursFromStart = Convert.ToInt32((!dictionary.ContainsKey("hoursFromStart")) ? ((object)0) : dictionary["hoursFromStart"]);
			promos.allPromos[i].neededLeague = Convert.ToInt32((!dictionary.ContainsKey("needLeague")) ? ((object)0) : dictionary["needLeague"]);
			promos.allPromos[i].isSingleUse = dictionary.ContainsKey("singleUse") && Convert.ToInt32(dictionary["singleUse"]) == 1;
			promos.allPromos[i].uniqueKey = promos.allPromos[i].startTime + promos.allPromos[i].inAppId + promos.allPromos[i].endTime;
			if (dictionary.ContainsKey("dollarPrice"))
			{
				string text = ((string)dictionary["dollarPrice"]).Replace(',', '.');
				float.TryParse((string)dictionary["dollarPrice"], NumberStyles.Any, CultureInfo.InvariantCulture, out promos.allPromos[i].inAppShowingPrice);
			}
			promos.allPromos[i].isCashPromo = (string)dictionary["cashOrGold"] == "cash";
			Dictionary<string, object> dictionary2 = dictionary["bonuses"] as Dictionary<string, object>;
			if (dictionary2 == null)
			{
				return;
			}
			promos.allPromos[i].promoBonuses = new PromoBonuses();
			int cash = Convert.ToInt32(dictionary2["cash"]);
			int gold = Convert.ToInt32(dictionary2["gold"]);
			int cashAlternativ = Convert.ToInt32(dictionary2["cashAlternative"]);
			int goldAlternative = Convert.ToInt32(dictionary2["goldAlternative"]);
			List<List<string>> list = new List<List<string>>();
			int productsListNumberFromJson = GetProductsListNumberFromJson(dictionary2, CupsManager.CurrentTier);
			lastLeagueUpdate = CupsManager.CurrentTier;
			bool promoHasBonuses = false;
			List<object> list2;
			if (productsListNumberFromJson == -1)
			{
				if (dictionary2.ContainsKey("market"))
				{
					list2 = dictionary2["market"] as List<object>;
					promoHasBonuses = true;
				}
				else
				{
					list2 = new List<object>();
				}
			}
			else
			{
				list2 = dictionary2["market_" + productsListNumberFromJson] as List<object>;
				promoHasBonuses = true;
			}
			for (int j = 0; j < list2.Count; j++)
			{
				list.Add((list2[j] as List<object>).OfType<string>().ToList());
			}
			promos.allPromos[i].promoBonuses = new PromoBonuses(cash, gold, list, promoHasBonuses, cashAlternativ, goldAlternative);
		}
		if (InAppPromoController.promosParsedFromJson != null)
		{
			InAppPromoController.promosParsedFromJson();
		}
	}

	private int GetProductsListNumberFromJson(Dictionary<string, object> jsonBonusObject, int myTier)
	{
		for (int num = myTier; num >= 0; num--)
		{
			if (jsonBonusObject.ContainsKey("market_" + num))
			{
				return num;
			}
		}
		return -1;
	}
}
